package main

import (
	"net/http"
	"net/url"
)

var STATIC_PROXY_MAP map[string]*Proxy
var DYNAMIC_PROXY []*Proxy

func init() {
	STATIC_PROXY_MAP = make(map[string]*Proxy)
}

func Handler() func(w http.ResponseWriter, r *http.Request) {
	//var proxies []*httputil.ReverseProxy
	//var regs []*regexp.Regexp
	for i := range FROM_LIST {
		remote, err := url.Parse(TO_LIST[i])
		if err != nil {
			continue
		}
		//var reg *regexp.Regexp
		if FROM_LIST[i][0] == '^' {
			DYNAMIC_PROXY = append(DYNAMIC_PROXY, NewProxy(FROM_LIST[i], remote))
			//reg = regexp.MustCompile(FROM_LIST[i])
		} else {
			STATIC_PROXY_MAP[FROM_LIST[i]] = NewProxy("", remote)
			//reg = regexp.MustCompile("^" + FROM_LIST[i])
		}
		//proxy := &httputil.ReverseProxy{
		//	Director:       requestFactory(remote, reg),
		//	//ModifyResponse: responseFactory(value, remote, reg),
		//}
		//proxies = append(proxies, proxy)
		//regs = append(regs, reg)
	}
	return func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/404" {
			http.NotFound(w, r)
			return
		}
		//检查静态
		for k, v := range STATIC_PROXY_MAP {
			if r.URL.Path == k {
				v.doProxy(w, r)
				return
			}
		}
		//检查动态
		if DYNAMIC_PROXY != nil {
			for _, v := range DYNAMIC_PROXY {
				if v.canProxy(r.URL.Path) {
					v.doProxy(w, r)
					return
				}
			}
		}

		http.NotFound(w, r)

		//var i = len(proxies)
		//for i > 0{
		//	i--
		//	if regs[i].MatchString(r.URL.Path) {
		//		proxies[i].ServeHTTP(w,r)
		//		return
		//	}
		//}
		////404
		//http.NotFound(w, r)
		//proxy.ServeHTTP(w, r)
	}
}

//func getContentType(r *http.Request) string {
//	var contentType = r.Header.Get("Content-Type")
//	if contentType == "" {
//		contentType = r.Header.Get("content-type")
//	}
//	return contentType
//}

//func responseFactory(location *LocationBlock, remote *url.URL, reg *regexp.Regexp) func(r *http.Response) error {
//	return func(response *http.Response) error {
//
//	}
//}
